//
//  FriendTravelTableViewController.m
//  ShareNavigation
//
//  Created by 水木 傅 on 12-5-16.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "FriendTravelTableViewController.h"
#import "SingletonUser.h"
#import "ASIFormDataRequest.h"
#import "FriendTravelInfoCell.h"
#import "FriendTravelDetailViewController.h"
#import "SingletonFriendInfo.h"

@implementation FriendTravelTableViewController

@synthesize resultArray,returnFindXML,switchString,friendTravelInfo,currentUserID;

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.resultArray = [[NSMutableArray alloc]initWithObjects: nil];
    self.friendTravelInfo = [[FriendTravelInfo alloc] init];
    currentUserID = [SingletonUser shareManager].UserID;
    [self getData:currentUserID];
}

-(void)viewDidUnload
{
    [self setResultArray:nil];
    [self setReturnFindXML:nil];
    [self setSwitchString:nil];
    [self setFriendTravelInfo:nil];
    [self setCurrentUserID:nil];
    [super viewDidUnload];
}

-(void) getData:(NSString *)userID
{
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/FriendTravelInfo.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setPostValue:[self currentUserID]  forKey:@"UserID"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestDataFinished:)];
    [request setDidFailSelector:@selector(requestDataFailed:)];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    //---  发送请求信息  ----
    [request startAsynchronous];    
    NSLog(@"getData");
}

-(void) requestDataFinished:(ASIHTTPRequest *)request
{
    NSString *response = request.responseString;
    NSLog(@"%@",response);
    if([response isEqualToString:@"FALSE"])
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@"提醒"
                 message:@"服务器连接错误，请稍候再试"
                 delegate:nil
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        returnFindXML = response;
        [self analysisXML:returnFindXML];
    }
    
}

-(void) requestDataFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedFailureReason]);
}


#pragma ---  分析xml  ---
-(void) analysisXML:(NSString *) XMLstring
{
    NSMutableString *xmlStr = [NSMutableString stringWithString:XMLstring];
    NSData *data = [NSData dataWithBytes:[xmlStr UTF8String] length:[xmlStr lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    
    //---  设置xml数据  ---
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    [parser setDelegate: self];
    [parser parse];
}

//---  遍历xml节点  ---
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    //NSLog(@"name.:  %@",elementName);
    switchString = elementName;
}

//---  当xml有值，则调用函数  ---
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    //NSLog(@"value:   %@",string);
    //---  对每个值进行分析  ---
    if ([switchString isEqualToString:@"UUID"]) 
    {
        friendTravelInfo.UUID = string;
    }
    else if([switchString isEqualToString:@"UserID"])
    {
        friendTravelInfo.userID = string;
    }
    else if([switchString isEqualToString:@"HeadPhoto"])
    {
        friendTravelInfo.headPhoto = string;
    }
    else if([switchString isEqualToString:@"Time"])
    {
        friendTravelInfo.signInTime = string;
    }
    else if([switchString isEqualToString:@"TravelSignature"])
    {
        friendTravelInfo.travelSignature = string;
    }
    else if([switchString isEqualToString:@"Location"])
    {
        friendTravelInfo.location = string;
    }
    else if([switchString isEqualToString:@"HasImage"])
    {
        if([string isEqualToString:@"0"])
        {
            NSLog(@"%@,  000000",string);
            friendTravelInfo.hasImage = FALSE;
        }
        else
        {
             NSLog(@"%@,  1111",string);
            friendTravelInfo.hasImage = TRUE;
        }
    }
}

//---  遇到结束标记，调用该函数  ---
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    //NSLog(@"结束标记：   %@",elementName);
    if([elementName isEqualToString:@"OneFriendTravel"])
    {
        FriendTravelInfo *temp = [[FriendTravelInfo alloc] init];
        [temp SetValueFromeObject:self.friendTravelInfo];
        [resultArray addObject:temp];
        [friendTravelInfo SetEmpty];
    }
    
    //---  xml解析完毕  ---
    if([elementName isEqualToString:@"body"])
    {
        if([[self resultArray] count] == 0)
        {
            UIAlertView *alert;
            alert = [[UIAlertView alloc]
                     initWithTitle:@"提醒"
                     message:@"无好友信息"
                     delegate:nil
                     cancelButtonTitle:@"返回"
                     otherButtonTitles:nil];
            [alert show];
        }
        [self.tableView reloadData];
    }
}

//---  通过名称获取图片  ----
-(UIImage *) getPicture :(NSString *)imageName
{
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/upload/%@.jpg",imageName];
    NSURL *url  =[NSURL URLWithString: urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *archivePath = [documentsDirectory 
                             stringByAppendingPathComponent:
                             [NSString stringWithFormat:@"%@.jpg",imageName]];
    
    [request setDownloadDestinationPath:archivePath];
    return [UIImage imageWithContentsOfFile:archivePath];
}

#pragma ---  tableviewDatasource  ---
//---  这个是返回tablview的列数的  ---
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//---  返回的是tableview的行数，一共有多少行  ---
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [resultArray count];
}

//返回每一个对应的单元cell的东西
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FriendTravelInfoCell *cell = (FriendTravelInfoCell *)[tableView dequeueReusableCellWithIdentifier:@"FriendTravelCell"];
    FriendTravelInfo *sign = [self.resultArray objectAtIndex:indexPath.row];
    //NSLog(@"===  %@  ===",sign.imageName);
    if(![sign.headPhoto isEqualToString:@""])
    {
        cell.headImageView.image = [self getPicture:sign.headPhoto];
    }
    else
    {
        cell.headImageView.image = [UIImage imageNamed:@"null.jpg"];
    }
    cell.userIDLabel.text = sign.userID;
    cell.signInTime.text = sign.signInTime;
    cell.travelSignature.text = sign.travelSignature;
    cell.tag = indexPath.row;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%d",indexPath.row);
}

#pragma  ---  切换到列表模式时候，传递数据  ---
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"FriendDetailTravel"])
    {
        NSLog(@"%d",[sender tag]);
        FriendTravelDetailViewController *controller = (FriendTravelDetailViewController *)segue.destinationViewController;
        FriendTravelInfo *sign = [self.resultArray objectAtIndex:[sender tag]];
        
        controller.UUID = sign.UUID;
        
        [SingletonFriendInfo shareManager].UUID = sign.UUID;
        [SingletonFriendInfo shareManager].headPhoto = sign.headPhoto;
        
        [SingletonFriendInfo shareManager].userID = sign.userID;
        [SingletonFriendInfo shareManager].signInTime = sign.signInTime;
        [SingletonFriendInfo shareManager].travelSignature = sign.travelSignature;
        [SingletonFriendInfo shareManager].location = sign.location;
        if(sign.hasImage == TRUE)
        {
            NSLog(@"SIGN TRUE");
            [SingletonFriendInfo shareManager].hasImage = TRUE;
        }
        else
        {
             NSLog(@"SIGN FALSE");
             [SingletonFriendInfo shareManager].hasImage = FALSE;
        }

        
        NSLog(@"++++%@+++",[SingletonFriendInfo shareManager].location);
    }
}
@end
















